/**
 * 扩展中间件
 *
 * 模块初始化，访问配置等功能
 */
import { ssrMiddleware } from 'quasar/wrappers'
import express from 'express';
import path from 'path';
import wf from 'src-ssr/util/workflow';
import localStorage from 'src-ssr/util/levelDB';
// import rsa from 'src-ssr/util/rsa';
import mDict from 'src-ssr/util/dictionary';

// 数据库帮助初始化
// require('src-ssr/db/tableHelper').init();
import tableHelper from 'src-ssr/db/tableHelper';
tableHelper.init();

// levelDB初始化
localStorage.init().then(() => {
  // rsa.init(); // rsa初始化
});

// 后端全局字典初始化
mDict.refresh();

// "async" is optional;
// more info on params: https://v2.quasar.dev/quasar-cli/developing-ssr/ssr-middlewares
export default ssrMiddleware(async ({ app /*, resolveUrlPath, publicPath, render */ }) => {
  // something to do with the server "app"
  app.use(express.json({ limit: '10mb' })); // 数据包发送限制

  const dir = process.env.DEV ? '../..' : '..';

  app.use('/uploads', express.static(path.join(path.resolve(__dirname, dir), 'uploads'))); // 静态目录
  app.use('/', express.static(path.join(path.resolve(__dirname, dir), 'uploads/mp')));

  if (process.env.DEV) {
    wf.init(process.env.DEV_WS_PORT);
  }

  // 自定义跨域中间件
  const allowCors = function (req, res, next) {
    res.header('Access-Control-Allow-Origin', req.headers.origin);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    res.header('Access-Control-Allow-Credentials', 'true');
    next();
  };
  app.use(allowCors);// 使用跨域中间件
});
